package kr.hkit.androidcomplete03.ch281;

import java.io.FileOutputStream;

import kr.hkit.androidcomplete03.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Ch281ActivityMain extends ListActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
				R.array.chapter281, android.R.layout.simple_list_item_1);
		setListAdapter(adapter);
		new XmlJsonMake().execute();

	}

	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = null;
		switch (position) {
		case 0:
			intent = new Intent(this, DomParser.class);
			break;
		case 1:
			intent = new Intent(this, SaxParser.class);
			break;
		case 2:
			intent = new Intent(this, JsonParser.class);
			break;
		case 3:
			intent = new Intent(this, PullParser.class);
			break;
		case 4:
			intent = new Intent(this, DaeguNotice.class);
			break;

		}
		startActivity(intent);
	}// end of method onListItemClick()

	private class XmlJsonMake extends AsyncTask<Void, Void, Void> {
		ProgressDialog ProgressDlg;

		@Override
		protected void onPreExecute() {
			ProgressDlg = ProgressDialog.show(Ch281ActivityMain.this,
					"Wait. . .", "order.xml & order.json is doing . . .");
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				FileOutputStream fos = openFileOutput("order.xml", MODE_PRIVATE);
				String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
						+ "<order>\n"
						+ " <item Maker=\"Samsung\" Price=\"23000\">Mouse</item>\n"
						+ " <item Maker=\"LG\" Price=\"12000\">KeyBoard</item>\n"
						+ " <item Price=\"156000\" Maker=\"Western Digital\">HDD</item>\n"
						+ "</order>";
				fos.write(str.getBytes());
				fos = openFileOutput("order.json", MODE_PRIVATE);
				String Json = "[\n"
						+ " {\"Product\":\"Mouse\", \"Maker\":\"Samsung\", \"Price\":23000},\n"
						+ "{\"Product\":\"KeyBoard\", \"Maker\":\"LG\", \"Price\":12000},\n"
						+ "{\"Product\":\"HDD\", \"Maker\":\"Western Digital\", \"Price\":156000} \n"
						+ "]";

				fos.write(Json.getBytes());
				fos.close();
				Thread.sleep(3000);
			} catch (Exception e) {
				Log.d("XmlParser", e.getMessage());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			ProgressDlg.dismiss();
			Toast.makeText(getApplicationContext(),
					"order.xml & order.json make", 0).show();
		}

	}// end of class XmlJsonMake{}
}
